package cn.didi.feidi.javabackend.mysql.jpa.controller;

import cn.didi.feidi.javabackend.mysql.jpa.repository.UserJpaRep;
import cn.didi.feidi.javabackend.mysql.jpa.user.User;
import cn.didi.feidi.javabackend.mysql.jpa.waterDeliver.WaterDeliver;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


/**
 * Created by Administrator on 2017/7/7.
 */
@RestController
@Transactional(readOnly = false)
@ComponentScan(basePackages={"cn.didi.feidi.javabackend.mysql.jpa.repository"})
public class UserController {
    @Autowired
    UserJpaRep userRepository;

    @Autowired
    SessionFactory sessionFactory;

    @Autowired
    HibernateTemplate hibernateTemplate;

    /**
     * 例子，访问http://localhost:8080/userxxol/list
     * @return [{"id":2,"name":"xiaoming","createdate":1499345500000,"roles":[{"id":2,"name":"admin"}]},{"id":3,"name":"陈鸿","createdate":1499345515000,"roles":[]}]
     */

    @RequestMapping("/getUserById")
    public User getUserById(@RequestParam String id){
        User user = userRepository.findOne(id);
        return user;
    }

    @RequestMapping("/addUser")
    @ResponseBody
    public String addUser(@RequestBody User user){
        userRepository.save(user);
        return "OK";
    }

    @RequestMapping("/updateUser")
    @ResponseBody
    public String updateUser(@RequestBody User user){
        userRepository.delete(user.getUserId());
        userRepository.save(user);
        return "OK";
    }

    @RequestMapping("/deleteUser")
    @ResponseBody
    public String deleteUserById(@RequestParam String id){
        userRepository.delete(id);
        return "OK";
    }

    @RequestMapping("/getUsersByName")
    public List<?> getUsersByName(@RequestParam String name){
        DetachedCriteria criteria = DetachedCriteria.forClass(User.class).createCriteria("user");
        Map<String, String> params = new HashMap<String, String>();
        return hibernateTemplate.findByCriteria(criteria.add(Restrictions.allEq(params)));
    }

    @RequestMapping("/updateUserById")
    //使用hibernate的update动态更新对象属性
    public String updateUserById(@RequestBody Map<String, Object> params) throws Exception{
        String id = (String)params.get("id");
        User user = getUserById(id);
        Iterator<Map.Entry<String, Object>> iterator = params.entrySet().iterator();
        //使用反射，更新waterDeliver部分属性
        while(iterator.hasNext()){
            Map.Entry<String, Object> entry = iterator.next();
            if(entry.getKey().equals("id"))
                continue;
            String methodName = "set" + entry.getKey().substring(0, 1).toUpperCase() + entry.getKey().substring(1);
            Field field = User.class.getDeclaredField(entry.getKey());
            Method method = User.class.getMethod(methodName, field.getType());
            Object value = entry.getValue();
            if(field.getType().equals(float.class)){
                value = Float.parseFloat(value.toString());
            }
            method.invoke(user, value);
        }
        //动态更新waterDeliver部分属性，而不会全部更新影响效率
        hibernateTemplate.update(user);
        return "OK";
    }


}
